package view;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import javax.swing.JFormattedTextField;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeListener;
import javax.swing.text.JTextComponent;

import model.Skill;
import controller.TestSkiller;

@SuppressWarnings({ "serial", "unused" })
public class TestSpinner extends JSpinner {
	
	private int min;
	private int max;
	private Skill skill = null;
	private SpinnerNumberModel model;
	
	// TODO remove when unused! - dont cause of job and upgrade spinner
	public TestSpinner(int initial, int min, int max, TestSkiller controller) {
		this.min = min;
		this.max = max;
		
		model = new SpinnerNumberModel(initial, min, max, 1);
		setModel(model);
		addChangeListener(controller);
		
		addFeatureHandlers();
	}

	private void addFeatureHandlers() {
		addMouseWheelListener(new MouseWheelListener() {
			public void mouseWheelMoved(MouseWheelEvent e) {
				subtract(e.getWheelRotation());
			}
		});
		
		
		((JSpinner.DefaultEditor) getEditor()).getTextField().addFocusListener(new FocusListener() {

			public void focusGained(final FocusEvent e) {
				SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        ((JTextComponent) e.getSource()).selectAll();
                    }
                });
			}

			public void focusLost(FocusEvent e) {
			}
		});
		
		((JSpinner.DefaultEditor) getEditor()).getTextField().addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				if(e.getKeyChar() == '\u007F') {
					System.out.println("true, setting to zero");
					setValue(0);
				}
			}
		});
	}
	
	public TestSpinner(Skill skill, boolean spSpinner, int min, int max,
			ChangeListener controller) {
		this.min = min;
		this.max = max;
		this.skill = skill;
		
		int initial = (spSpinner) ? skill.getSpValue() : skill.getSkillValue(); 
		
		setModel(new SpinnerNumberModel(initial, min, max, 1));
		addChangeListener(controller);
		
		addFeatureHandlers();
	}

	private void subtract(int value) {
		int nextValue = getValueInteger() - value;
		
		if(nextValue > max) setValue(max);
		else if(nextValue < min) setValue(min);
		else setValue(nextValue);
	}
	
	
	public int getValueInteger() {
		return Integer.parseInt(getValue().toString());
	}
	
	public Skill getSkill() {
		return skill;
	}
	
	public JFormattedTextField textField(){
		return ((JSpinner.DefaultEditor) getEditor()).getTextField();
	}
	
	public void setMinimum(int min) {
		model.setMinimum(min);
	}
}
